<template>
  <el-row>
    <el-col :span="8" class="el-col">
      <label>客户名称：</label>
    </el-col>
    <el-col :span="16">
      <el-autocomplete
        class="el-autocomplete"
        v-model="customerName"
        size="small"
        @select="handleSelect"
        :fetch-suggestions="querySearch"
      ></el-autocomplete>
    </el-col>
  </el-row>
</template>
<script>
import { getAllCustomer } from '../../api/userCenterApi.js'

export default {
  name: 'MySearchCustomer',
  props: {
    value: {
      required: false,
      default: ''
    }
  },
  data() {
    return {
      customerList: [],
      customerName: ''
    }
  },
  watch: {
    customerName(value) {
      if (!value) {
        this.handleSelect({ id: '' })
      }
    },
    value(value) {
      if (!value) {
        this.customerName = ''
      }
    }
  },
  methods: {
    querySearch(queryString, cb) {
      if (queryString) {
        cb(this.customerList.filter(this.createFilter(queryString)))
      } else {
        cb(this.customerList)
      }
      let results = queryString
        ? this.customerList.filter(this.createFilter(queryString))
        : this.customerList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return customer => {
        return (
          customer.customerName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        )
      }
    },
    loadAllCustomer() {
      const self = this
      getAllCustomer().then(data => {
        self.customerList = data.list
        for (let i = 0; i < self.customerList.length; i++) {
          self.customerList[i].value = self.customerList[i].customerName
        }
      })
    },
    handleSelect(item) {
      this.$emit('input', item.id)
    }
  },
  mounted() {
    this.loadAllCustomer()
  }
}
</script>
<style lang="scss" scoped>
.el-row {
  line-height: 32px;

  .el-col {
    text-align: right;
  }

  .el-autocomplete {
    width: 100%;
  }
}
</style>

